<template>
  <div v-elclickoutside="handleClose" ref="reference"
       :class="[disabled ? 'is_disabled' : 'is_valid', { 'is_focus': visible }]"
       wrap="wrap" class="wk-user-dep-select xh-form-border"
       @click="containerClick">

    <div class="el-select__tags">
      <template v-for="(item, index) in showUserSelects" :key="`user${index}`">
        <span class="user-item text-one-line">{{ item[userPropsValue.label] }}
        <i class="delete-icon el-icon-close" @click.stop="deleteuser(index)"/>
      </span>
      </template>

      <template v-for="(item, index) in showDepSelects" :key="`dep${index}`">
        <span class="user-item text-one-line">{{ item[depPropsValue.label] }}
        <i class="delete-icon el-icon-close" @click.stop="deleteDep(index)"/>
      </span>
      </template>

    </div>
    <el-tooltip v-if="(depSelects.length + userSelects.length) > max" :content="getTooltipText()" effect="dark"
                placement="top">
      <i class="el-icon-more"/>
    </el-tooltip>
    <i :class="['el-icon-arrow-up', { 'is-reverse' : visible}]"/>
    <div v-if="(depSelects.length + userSelects.length) == 0" class="user-placeholder text-one-line">{{ placeholder }}
    </div>

    <WkSelectDropdown v-loading="loading" v-show="visible && !disabled" ref="popper">
      <template v-slot:default>
        <WkUserDep ref="userDep"                   :radio="radio"
                   :user-props="userPropsValue"
                   :user-value="userDataValue"
                   :props="props"
                   :dep-props="depPropsValue"
                   :dep-value="depDataValue"
                   :disabled="disabled"
                   @userChange="userChange"
                   @depChange="depChange"
                   @close="visible = false"/>
      </template>
    </WkSelectDropdown>
  </div>
</template>

<script setup>
import WkSelectDropdown from '../WkDepSelect/src/SelectDropdown.vue'
import WkUserDep from './src/WkUserDep.vue'
import merge from '/src/utils/merge.js'
import {useErpUserStore} from "../../../../store/modules/usererp.js";
import {debounce} from 'throttle-debounce'
import {valueEquals} from '/src/utils/elementui.js'
import {objDeepCopy} from '/src/utils/index.js'

// 同 WkUserDep.vue 中的 DefaultWkUserDep
const DefaultWkUserDep = {
  // 树结构请求和参数
  request: null,
  params: null,
  // 默认的搜索人资和管理端人员请求
  // isHrm: false, // 替换为 dataType 默认 manage 其余 hrm
  dataType: 'manage', // 默认管理端
  // userOptions: null, // 固定数据，后可以放入 props options
  isList: false // 默认是树形接口，如果是列需设置为true
}

defineOptions({
  name: 'WkUserDepSelect',
})

const props = defineProps({
  radio: Boolean,
  // 展示限制
  max: {
    type: Number,
    default: 2
  },
  props: {
    type: Object,
    default: () => {
      return {}
    }
  },

  depProps: {
    type: Object,
    default: () => {
      return {}
    }
  },

  userProps: {
    type: Object,
    default: () => {
      return {}
    }
  },

  placeholder: {
    type: String,
    default() {
      return '请选择'
    }
  },
  // eslint-disable-next-line vue/require-prop-types
  depValue: {
    required: true
  },
  // eslint-disable-next-line vue/require-prop-types
  userValue: {
    required: true
  },
  // 自定义请求和 参数
  // request: Function,
  // params: Object,
  depOptions: Array,
  userOptions: Array,
  disabled: {
    type: Boolean,
    default: false
  },
  popperAppendToBody: {
    type: Boolean,
    default: true
  }
})

const optionData = reactive({
  visible: false,
  tabType: 'user',
  depDataValue: [], // 校准传入值
  userDataValue: [],
  loading: false
})
const {visible, tabType, depDataValue, userDataValue, loading} = toRefs(optionData)

const emits = defineEmits(['visible-change', 'update:depValue', 'update:depValue', 'focus', 'change'])

const erpUserStore = useErpUserStore()

// 实际展示的数据
const showUserSelects = computed(() => {
  if (userSelects.value && userSelects.value.length > props.max) {
    return userSelects.value.slice(0, props.max)
  }
  return userSelects.value
})

const showDepSelects = computed(() => {
  let max = 0
  if (userSelects.value && userSelects.value.length < props.max || !userSelects.value) {
    max = props.max - userSelects.value.length
  }

  if (max > 0 && depSelects.value) {
    return depSelects.value.slice(0, props.max)
  }
  return []
})

const userOptionsList = computed(() => {
  if (config.value.dataType === 'manage') {
    return erpUserStore.userList
  } else if (config.value.dataType === 'hrm') {
    return erpUserStore.hrmUserList
  }
})

const depOptionsList = computed(() => {
  if (config.value.dataType === 'manage') {
    // 以缓存中的全部数据为id转对象的源
    return erpUserStore.deptList
  } else if (config.value.dataType === 'hrm') {
    return erpUserStore.hrmDeptList
  }
})

// 选择的数据
const depSelects = computed(() => {
  if (!depOptionsList.value.length) {
    return []
  }

  return getSelectList()
})

// 员工选择的数据
const userSelects = computed(() => {
  if (!userOptionsList.value.length) {
    return []
  }

  return userOptionsList.value.filter(item => optionData.userDataValue.includes(item[userPropsValue.value]))
})

const config = computed(() => {
  return merge({...DefaultWkUserDep}, props.props || {})
})

const depPropsValue = computed(() => {
  const defaultValue = {
    value: 'deptId',
    label: 'name'
  }
  if (config.value.dataType === 'hrm') {
    defaultValue.value = 'deptId'
    defaultValue.label = 'name'
  }
  if (props.depProps) {
    return {...defaultValue, ...props.depProps}
  } else {
    return defaultValue
  }
})

const userPropsValue = computed(() => {
  const defaultValue = {
    value: 'userId',
    label: 'realname'
  }
  if (config.value.dataType === 'hrm') {
    defaultValue.value = 'employeeId'
    defaultValue.label = 'employeeName'
  }
  if (props.userProps) {
    return {...defaultValue, ...props.userProps}
  } else {
    return defaultValue
  }
})

watch(visible, (val) => {
  if (!val) {
    this.broadcast('WkSelectDropdown', 'destroyPopper')
  } else {
    this.broadcast('WkSelectDropdown', 'updatePopper')
  }
  emits('visible-change', val)
})

watch(() => props.depValue, () => {
  depVerifyValue()
})

/**
 * 更新值
 */
watch(depDataValue, (newValue, oldValue) => {
  if (!valueEquals(newValue, oldValue)) {
    if (props.radio) {
      emits('update:depValue', optionData.depDataValue && optionData.depDataValue.length ? optionData.depDataValue[0] : '')
    } else {
      emits('update:depValue', optionData.depDataValue)
    }
  }
})

watch(() => props.userValue, () => {
  userVerifyValue()
})

/**
 * 更新值
 */
watch(userDataValue, (newVal, oldVal) => {
  if (!valueEquals(newVal, oldVal)) {
    if (props.radio) {
      emits('update:userValue', optionData.userDataValue && optionData.userDataValue.length ? optionData.userDataValue[0] : '')
    } else {
      emits('update:userValue', optionData.userDataValue)
    }
  }
})

watch(() => props.depProps, () => {
  requestDepList()
}, {
  immediate: true
})

watch(() => props.userProps, () => {
  requestUserList()
}, {
  immediate: true
})
let debounceUserDeptChange = () => {
}

function created() {
  debounceUserDeptChange = debounce(300, userDeptChange)
}

created();


onMounted(() => {
  depVerifyValue()
  userVerifyValue()
})

/**
 * 获取展示的数组
 */
function getSelectList() {
  const list = []
  recursionOptions(depOptionsList.value, optionData.depDataValue, list)
  return list
}

function recursionOptions(options, depSelects, list) {
  options.forEach(item => {
    if (depSelects.includes(item[depPropsValue.value])) {
      list.push(item)
    }


    if (item.children) {
      recursionOptions(item.children, depSelects, list)
    }
  })
}

/**
 * 处理值逻辑
 */
function depVerifyValue() {
  // 多选的默认值 校准为数组  单选校准为number
  if (!props.radio && !Array.isArray(props.depValue)) {
    emits('update:depValue', [])
  }

  if (props.radio && (Array.isArray(props.depValue) || props.depValue === null || props.depValue === undefined)) {
    emits('update:depValue', '')
  }

  if (props.radio) {
    if (props.depValue !== optionData.depDataValue) {
      if (props.depValue) {
        optionData.depDataValue = [parseInt(props.depValue)]
      } else {
        optionData.depDataValue = []
      }
    }
  } else {
    if (!valueEquals(props.depValue, optionData.depDataValue)) {
      if (props.depValue && props.depValue.length) {
        const firstItem = props.depValue[0]
        if (firstItem[props.depPropsValue.value]) {
          props.depDataValue = props.depValue.map(item => item[props.depPropsValue.value])
        } else {
          props.depDataValue = objDeepCopy(props.depValue)
        }
      } else {
        props.depDataValue = []
      }
    }
  }
}

/**
 * 获取请求
 */
function requestDepList() {
  console.log("requestDepList")
  if (config.value.dataType === 'manage') {
    erpUserStore.debounceGetDeptList()
  } else if (config.value.dataType === 'hrm') {
    erpUserStore.debounceGetHrmDeptList()
  }
}

function handleClose() {
  optionData.visible = false
}


/**
 * 删除
 */
function deleteDep(index) {
  if (!props.disabled) {
    // 直接 splice ,depDataValue watch 的老旧值相同，复制之后新旧值不相同。暂时解决
    const depDataValue = objDeepCopy(optionData.depDataValue)
    depDataValue.splice(index, 1)
    optionData.depDataValue = depDataValue
    wkDepChange()
  }
}

/**
 * chang 事件
 */
function wkDepChange() {
  nextTick(() => {
    if (props.radio) {
      this.dispatch('ElFormItem', 'el.form.change', optionData.depDataValue && optionData.depDataValue.length ? optionData.depDataValue[0] : '')
    } else {
      this.dispatch('ElFormItem', 'el.form.change', optionData.depDataValue)
    }
    debounceUserDeptChange('dep')
  })
}

function containerClick() {
  if (!props.disabled) {
    optionData.visible = !optionData.visible
  }
}


/** *** 员工 */
/**
 * 处理值逻辑
 */
function userVerifyValue() {
  // 多选的默认值 校准为数组  单选校准为number
  if (!props.radio && !Array.isArray(props.userValue)) {
    emits('update:userValue', [])
  }

  if (props.radio && (Array.isArray(props.userValue) || props.userValue === null || props.userValue === undefined)) {
    emits('update:userValue', '')
  }

  if (props.radio) {
    if (props.userValue !== optionData.userDataValue) {
      if (props.userValue) {
        optionData.userDataValue = [parseInt(props.userValue)]
      } else {
        optionData.userDataValue = []
      }
    }
  } else {
    if (!valueEquals(props.userValue, optionData.userDataValue)) {
      if (props.userValue && props.userValue.length) {
        const firstItem = props.userValue[0]
        if (firstItem[props.userPropsValue.value]) {
          optionData.userDataValue = props.userValue.map(item => item[props.userPropsValue.value])
        } else {
          optionData.userDataValue = objDeepCopy(props.userValue)
        }
      } else {
        optionData.userDataValue = []
      }
    }
  }
}

/**
 * 获取请求
 */
function requestUserList() {
  if (config.value.dataType === 'manage') {
    // 以缓存中的全部数据为id转对象的源
    // this.userOptionsList = this.userList
    // this.loading = !this.userList || this.userList.length === 0
    // this.$store.dispatch('GetUserList').then(res => {
    //   this.userOptionsList = this.userList
    //   this.loading = false
    // }).then(() => {
    //   this.loading = false
    // })

    erpUserStore.debounceGetUserList()
  } else if (config.value.dataType === 'hrm') {
    // 以缓存中的全部数据为id转对象的源
    // this.userOptionsList = this.hrmUserList
    // this.loading = !this.hrmUserList || this.hrmUserList.length === 0
    // this.$store.dispatch('GetHrmUserList').then(res => {
    //   this.userOptionsList = this.hrmUserList
    //   this.loading = false
    // }).then(() => {
    //   this.loading = false
    // })
    erpUserStore.debounceGetHrmUserList()
  }
}

/**
 * 删除
 */
function deleteuser(index) {
  if (!props.disabled) {
    optionData.userDataValue.splice(index, 1)
    // this.$emit('change', this.userDataValue, this.userSelects)
    wkUserChange()
  }
}

/**
 * chang 事件
 */
function wkUserChange() {
  nextTick(() => {
    if (props.radio) {
      this.dispatch('ElFormItem', 'el.form.change', optionData.userDataValue && optionData.userDataValue.length ? optionData.userDataValue[0] : '')
    } else {
      this.dispatch('ElFormItem', 'el.form.change', optionData.userDataValue)
    }
    debounceUserDeptChange('user')
  })
}

/**
 * 更多提示语
 */
function getTooltipText() {
  const structures = depSelects.value || []
  let strName = structures.map(item => item[props.depPropsValue.label]).join('、')

  const users = userSelects.value || []
  const userName = users.map(item => item[props.userPropsValue.label]).join('、')

  if (strName && userName) {
    strName += '、'
  }
  return strName + userName
}

/**
 * change 事件
 */
function userChange(val) {
  optionData.userDataValue = val
  wkUserChange()
}

/**
 * change 事件
 */
function depChange(val) {
  optionData.depDataValue = val
  wkDepChange()
}

function userDeptChange(type) {
  emits('change', optionData.userDataValue, optionData.depDataValue, userSelects.value, depSelects.value, type)
}
</script>


<script>
// import Emitter from 'element-ui/lib/mixins/emitter'
// import { valueEquals } from 'element-ui/lib/utils/util'
import {mapStores} from "pinia";

export default {
  components: {
    // WkSelectDropdown,
    // WkUserDep
  },
  // mixins: [Emitter],

  props: {},

  data() {
    return {}
  },

  computed: {
    // ...mapStores(useErpUserStore),
  },
  watch: {},
  methods: {}
}
</script>
<style lang="scss" scoped>
.wk-user-dep-select {
  height: 34px;
  position: relative;
  border-radius: $xr-border-radius-base;
  font-size: 13px;
  background-color: white;
  border: 1px solid #e6e6e6;
  color: #333333;
  width: 180px;
  padding: 0 20px 0 5px;
  cursor: pointer;

  .user-item {
    padding: 5px 15px 5px 5px;
    background-color: #F3F7FF;
    border-radius: 4px;
    margin: 3px;
    max-width: 80px;
    position: relative;
  }

  .user-placeholder {
    color: #ddd;
    line-height: 34px;
    cursor: pointer;
    user-select: none;
  }

  .delete-icon {
    color: #999;
    cursor: pointer;
    position: absolute;
    top: 8px;
    right: 2px;

    &:hover {
      color: $xr-color-primary;
    }
  }

  &:hover {
    border-color: #c0c4cc;
  }
}

.wk-user-dep-select.is_disabled {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  cursor: not-allowed;

  .user-item {
    background-color: #f0f4f8ea;
    color: #c0c4cc;
    cursor: not-allowed;
  }

  .delete-icon {
    color: #c0c4cc;
    cursor: not-allowed;
  }

  .user-placeholder {
    color: #c0c4cc;
    cursor: not-allowed;
  }
}

.wk-user-dep-select.is_valid:hover {
  border-color: #c0c4cc;
}

.wk-user-dep-select.is_focus {
  border-color: $xr-focus-border !important;
}

.el-icon-more {
  position: absolute;
  top: 5px;
  right: 20px;
  padding: 6px 10px;
  font-size: 12px;
  background-color: #F3F7FF;
  color: #666;
  border-radius: $xr-border-radius-base;

  &:hover {
    background-color: $xr-color-primary;
    color: white;
  }
}

.el-icon-arrow-up {
  position: absolute;
  top: 10px;
  right: 5px;
  transition: transform .3s;
  color: #c0c4cc;
  font-size: 14px;
  transition: transform .3s;
  transform: rotate(180deg);
  cursor: pointer;
}

.el-icon-arrow-up.is-reverse {
  transform: rotate(0deg);
}

:deep( .el-tabs) {
  .el-tabs__nav-wrap {
    padding: 0 15px;
  }

  .el-tabs__nav-wrap::after {
    height: 1px;
  }

  .el-tabs__header {
    margin: 0;
  }
}
</style>
